package com.bnlr.lrparking.appui.publish;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.google.gson.Gson;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.AddStallTypeBean;
import com.bnlr.lrparking.model.AlterPublishDetailBean;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.CarPlaceTypeMode;
import com.bnlr.lrparking.model.JsonBean;
import com.bnlr.lrparking.model.MyPublishBean;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.GetJsonDataUtil;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.lrparking.view.SampleEditTextWatcher;
import com.bnlr.lrparking.widget.ConvertHelper;
import com.bnlr.lrparking.widget.boarddialog.InputBoardDialog;
import com.bnlr.lrparking.widget.boarddialog.InputRentBoardDialog;
import com.bnlr.lrparking.widget.boarddialog.KeyBoardDialog;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 求租求购--发布界面
 */
public class PublishBegActivity extends BaseActivity {
    private Unbinder unbinder;
    @BindView(R.id.tv_nav_title)
    TextView tvTitle;

    @BindView(R.id.publish_title)
    ClearEditText publishTitle;
    @BindView(R.id.area_choose)
    TextView areaChoose;
    @BindView(R.id.type_choose)
    TextView typeChoose;
    @BindView(R.id.tv_ys)
    TextView tvYs;
    @BindView(R.id.et_name)
    ClearEditText etName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.et_publish_description)
    EditText etDescription;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.man)
    RadioButton rbMan;
    @BindView(R.id.rb_woman)
    RadioButton rbWoman;
    @BindView(R.id.text_count_limit)
    TextView textCountLimit;
    @BindView(R.id.agree_clause)
    CheckBox agreeCheckBox;
    @BindView(R.id.tv_publish_hint)
    TextView tvPublishHint;
    @BindView(R.id.publish)
    TextView tvPublish;
    private int tag;
    private String requestType = "20";
    private OptionsPickerView pvCustomOptions,pvOptions;
    private ArrayList<ArrayList<CarPlaceTypeMode>> carType2 = new ArrayList<>();
    private ArrayList<CarPlaceTypeMode> carType1 = new ArrayList<>();
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private String carPlaceId,selectAreaId;
    private String zjCount = "";
    private String username ,publishPhone;
    private MyPublishBean.DataBean dataBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_beg);
        unbinder = ButterKnife.bind(this);
        username = AppConfig.getInstance().getString("userName","");
        publishPhone = username;
        if (!username.equals("")) {
            tvPhone.setText(username.substring(0, 3) + "****" + username.substring(7));
        }
        Intent intent = getIntent();
        tag = intent.getIntExtra("publish_tag",0);
        dataBean = intent.getParcelableExtra("alter_publish");
        initValue();
        switch (tag) {
            case 3:
                tvTitle.setText("发布求租车位信息");
                requestType = "20";
                etDescription.setHint("(选填)请描述你对求租车位的具体要求！");
                break;
            case 4:
                tvTitle.setText("发布求购车位信息");
                requestType = "21";
                etDescription.setHint("(选填)请描述你对求购车位的具体要求！");
                break;
            default:
                break;
        }
        initJsonData();
        initListener();
        tvPublishHint.setText("1、为确保您的需求信息顺利审核，请不要填写无关的信息。\n" +
                "2、审核过程中，客服人员将会在24小时内(工作日)与您核对您的需求，请您保持电话畅通。");
    }

    /**
     * 修改发布信息
     */
    private void initValue() {
      if (dataBean != null) {
          try {
              mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
              mRequest.add("action", "GetEditSpaceDetail");
              mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
              mRequest.add("phonePara", Application.DEVICE_ID);
              mRequest.add("parkSpaceId", dataBean.getId());

              // 添加到请求队列+
              CallServer.getRequestInstance().add(baseContext, mRequest,
                      new CustomHttpListener<AlterPublishDetailBean>(baseContext, true, AlterPublishDetailBean.class) {
                          @Override
                          public void doWork(AlterPublishDetailBean data, String code) {
                              if (code.equals("1")) {
                                  if (data.getData() != null && data.getData().get(0) != null) {
                                      AlterPublishDetailBean.DataBean  bean =  data.getData().get(0);
                                      publishTitle.setText(ConvertHelper.convertToString(bean.getTitle()));
                                      areaChoose.setText(ConvertHelper.convertToString(bean.getShowArea()));
                                      selectAreaId =   ConvertHelper.convertToString(bean.getAreaId());
                                      typeChoose.setText(ConvertHelper.convertToString(bean.getSpaceTypeString()));
                                      carPlaceId =  ConvertHelper.convertToString(bean.getSpaceType());
                                      tvYs.setText(ConvertHelper.convertToString(bean.getPrice()) + ConvertHelper.convertToString(bean.getPriceUnit()));
                                      zjCount = ConvertHelper.convertToString(bean.getPrice());
                                      if (ConvertHelper.convertToString(bean.getUserName()).endsWith("先生")) {
                                          rbMan.setChecked(true);
                                          etName.setText(ConvertHelper.convertToString(bean.getUserName()).replace("先生",""));
                                      } else if (ConvertHelper.convertToString(bean.getUserName()).endsWith("女士")) {
                                          rbWoman.setChecked(true);
                                          etName.setText(ConvertHelper.convertToString(bean.getUserName()).replace("女士",""));
                                      } else {
                                          etName.setText(ConvertHelper.convertToString(bean.getPrice()));
                                      }
                                      tvPhone.setText(CommonUtil.formatPhoneNumber(bean.getPhone()));
                                      publishPhone = bean.getPhone();
                                      etDescription.setText(ConvertHelper.convertToString(bean.getDescription()));
                                  }
                              }

                          }
                          @Override
                          public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                              if (!code.equals("1")) {
                                  CarCommon carCommon = new CarCommon();
                                  carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                      @Override
                                      public void setSure() {
                                          finish();
                                      }
                                  });
                                  try {
                                      carCommon.ReminderDialog(PublishBegActivity.this,obj.getString("msg"),"提示");
                                  } catch (JSONException e) {
                                      e.printStackTrace();
                                  }
                              }
                          }
                      }, true);
          } catch (Exception e) {

          }
        }
    }

    private void initListener() {
        etDescription.addTextChangedListener(new SampleEditTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                int length = s.toString().length();
                textCountLimit.setText(length +"/300");
            }
        });
        agreeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    agreeCheckBox.setChecked(true);
                } else {
                    agreeCheckBox.setChecked(false);
                }
            }
        });
    }

    @OnClick({R.id.area_choose,R.id.type_choose,R.id.tv_ys,R.id.rl_agree,R.id.tv_issueagreement,R.id.publish
    ,R.id.tv_phone})
    public void begOnClick (View view) {
        switch (view.getId()) {
            case R.id.area_choose:
                ShowPickerView();
                break;
            case R.id.type_choose:
                if (carType1.size() > 0) {
                    initCustomOptionPicker();
                } else {
                    getCarPlaceType();
                }
                break;
            case R.id.tv_ys:
                if (tag == 3) {
                    InputRentBoardDialog dialog1 = new InputRentBoardDialog(this,zjCount,"元/月");
                    dialog1.setOnDialogResultListener(new InputRentBoardDialog.OnDialogResultListener() {
                        @Override
                        public void onResult(String result) {
                            if (!"cancel".equals(result)) {
                                tvYs.setText(result);
                                if (result.equals("")) {
                                    zjCount = "";
                                } else {
                                    zjCount = result.substring(0,result.length() -3 );
                                }
                            }
                        }
                    });
                    dialog1.show();
                } else if (tag == 4) {
                    InputBoardDialog dialog3 = new InputBoardDialog(this,zjCount,"元");
                    dialog3.setOnDialogResultListener(new InputBoardDialog.OnDialogResultListener() {
                        @Override
                        public void onResult(String result) {
                            if (!"cancel".equals(result)) {
                                tvYs.setText(result);
                                if (result.equals("")) {
                                    zjCount = "";
                                } else {
                                    zjCount = result.substring(0,result.length() -1 );
                                }

                            }
                        }
                    });
                    dialog3.show();
                }

                break;
            case R.id.rl_agree:
                if (agreeCheckBox.isChecked()) {
                    agreeCheckBox.setChecked(false);
                } else {
                    agreeCheckBox.setChecked(true);
                }
                break;
            case R.id.tv_phone:
                KeyBoardDialog dialog = new KeyBoardDialog(this,publishPhone);
                dialog.setOnDialogResultListener(new KeyBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String result) {
                        if (result.equals("some")) {
                            ToastUtils.showShort("此手机号无需再次验证");
                        } else if (!result.equals("fail")) {
                            publishPhone = result;
                            tvPhone.setText(publishPhone.substring(0, 3) + "****" + publishPhone.substring(7));
                        }
                    }
                });
                dialog.show();
                break;
            case R.id.tv_issueagreement:
                Intent intent=new Intent(baseContext,WebActivity.class);
                intent.putExtra("tag",7);
                startActivity(intent);
                break;
            case R.id.publish:
                publish();
                break;
            default:
                break;
        }
    }

    /**
     * 发布
     */
    private void publish() {
        if (agreeCheckBox.isChecked()) {
            ToastUtils.showShort("请您先同意发布信息服务协议");
            return;
        }
        String title = publishTitle.getText().toString();
        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort("发布标题不能为空");
            return;
        }
        String area = areaChoose.getText().toString();
        if (TextUtils.isEmpty(area)) {
            ToastUtils.showShort("请选择区域");
            return;
        }
        String carPlaceType = typeChoose.getText().toString();
        if (TextUtils.isEmpty(carPlaceType)) {
            ToastUtils.showShort("请选择车位类型");
            return;
        }
        String user = etName.getText().toString();
        if (TextUtils.isEmpty(user)) {
            ToastUtils.showShort("请填写姓名");
            return;
        }
        String desc = etDescription.getText().toString();
        tvPublish.setEnabled(false);
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "PublishSpace");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("type", requestType);
            if (dataBean != null) {
                mRequest.add("parkSpaceId",dataBean.getId());
            } else {
                mRequest.add("parkSpaceId",0);
            }
            mRequest.add("title", title);
            mRequest.add("areaId",selectAreaId);
            mRequest.add("description",desc);
            if (radioGroup.getCheckedRadioButtonId()==R.id.man) {
                mRequest.add("username",user+"先生");
            } else {
                mRequest.add("username",user+"女士");
            }
            mRequest.add("spacetype",carPlaceId);
            if (zjCount.equals("")) {
                zjCount = "0";
            }
            mRequest.add("price",zjCount);
            mRequest.add("phone",publishPhone);
            if (tag == 3) {
                mRequest.add("priceunit","元/月");
            } else {
                mRequest.add("priceunit","元");
            }

            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BaseArrayBean>(baseContext, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            if("1".equals(code)) {
                                CarCommon carCommon = new CarCommon();
                                carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                    @Override
                                    public void setSure() {
                                        startActivity(MyPublishActivity.class);
                                        finish();

                                    }
                                });
                                carCommon.ReminderDialog(PublishBegActivity.this,"您已发布成功，请等待审核。","提示");
                            } else {

                                try {
                                    ToastUtils.showShort(obj.getString("msg"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            tvPublish.setEnabled(true);
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    /**
     * 获取车位类型
     */
    private void getCarPlaceType() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "GetSpaceType");
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<AddStallTypeBean>(baseContext, true, AddStallTypeBean.class) {
                        @Override
                        public void doWork(AddStallTypeBean data, String code) {
                            if ("1".equals(code)) {
                                for (int i = 0; i < data.getData().size(); i++) {
                                    carType1.add(new CarPlaceTypeMode(data.getData().get(i).getKey()
                                            ,data.getData().get(i).getValue()));
                                    ArrayList<CarPlaceTypeMode> type1 = new ArrayList<>();
                                    for (int j = 0; j < data.getData().get(i).getData().size(); j++) {
                                        type1.add(new CarPlaceTypeMode
                                                (data.getData().get(i).getData().get(j).getKey(),data.getData().get(i).getData().get(j).getValue()));
                                    }
                                    carType2.add(type1);
                                }
                                initCustomOptionPicker();
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!code.equals("1")) {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }
    private void initCustomOptionPicker() {
        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = carType1.get(options1).getValue()+"-"+carType2.get(options1).get(option2).getValue() ;
                typeChoose.setText(tx);
                carPlaceId = carType2.get(options1).get(option2).getKey() +"";
            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        pvCustomOptions.setPicker(carType1,carType2);//添加数据
        pvCustomOptions.show();
    }
    /**
     * 初始化地区列表
     */
    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this,"province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i=0;i<jsonBean.size();i++){//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            if (jsonBean.get(i).getCities()== null || jsonBean.get(i).getCities().size()==0){
                CityList.add("");
                ArrayList<String> areaList = new ArrayList<>();
                areaList.add("");
                Province_AreaList.add(areaList);
            } else {
                for (int c=0; c<jsonBean.get(i).getCities().size(); c++){//遍历该省份的所有城市
                    String CityName = jsonBean.get(i).getCities().get(c).getName();
                    CityList.add(CityName);//添加城市
                    ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                    if (jsonBean.get(i).getCities().get(c).getAreas() == null
                            ||jsonBean.get(i).getCities().get(c).getAreas().size()==0) {
                        City_AreaList.add("");
                    }else {
                        for (int d=0; d < jsonBean.get(i).getCities().get(c).getAreas().size(); d++) {//该城市对应地区所有数据
                            String AreaName = jsonBean.get(i).getCities().get(c).getAreas().get(d).getName();
                            City_AreaList.add(AreaName);//添加该城市所有地区数据
                        }
                    }
                    Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                }
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }
    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
    private void ShowPickerView() {// 弹出选择器
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()+
                        options2Items.get(options1).get(options2)+
                        options3Items.get(options1).get(options2).get(options3);
                areaChoose.setText(tx);
                if ( options1Items.get(options1).getCities().size() == 0) {
                    selectAreaId = options1Items.get(options1).getId()+"";
                }else {
                    selectAreaId = options1Items.get(options1).getCities()
                            .get(options2).getAreas().get(options3).getId()+"";
                }

            }
        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setSubCalSize(15)//确定和取消文字大小
                .setTitleSize(18)//标题文字大小
                .setDividerColor(getResources().getColor(R.color.gray03_color))//设置分割线的颜色
                .setTitleColor(getResources().getColor(R.color.main_color))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色
                .setContentTextSize(18)
                .build();
        pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器
        pvOptions.show();

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
